from rest_framework.views import APIView
from meituan.models import Merchant
from django.http import Http404
from .serializers import MerchantSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework import generics
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.decorators import action

## API ViEW

class MerchantView(APIView):
    def get_object(self,pk):
        try:
            return Merchant.objects.get(pk=pk)
        except Merchant.DoesNotExist:
            raise Http404

    '''
    pk 为空的时候 获取到的是 全部商家列表
    pk 不为空的时候 活动的是 具体的某一个商家列表
    '''
    def get(self,request,pk=None):
        if pk:
            merchant = self.get_object(pk)
            serializer = MerchantSerializer(merchant)
            return Response(serializer.data)
        else:
            queryset = Merchant.objects.all()
            serializer = MerchantSerializer(instance=queryset, many=True)
            return Response(serializer.data)

    def put(self,request,pk):
        ## 获取商家
        merchant = self.get_object(pk)
        ## 将查询处理的数据 和 来自请求的数据进行关联 准备执行 验证和保存操作 这是一个 put 修改方法
        ## 使用 request.data 进行反序列化并更新商家实例
        result = MerchantSerializer(merchant,data=request.data)
        if result.is_valid():
            result.save()
            return Response(result.data,status=200)
        return Response(result.errors,status=400)

    def delete(self,request,pk=None):
        merchant = self.get_object(pk)
        merchant.delete()
        return Response(status=204)

